import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/controller/cache.dart';

//使用webview的方式打开书；此插件只支持apps，桌面版和web版暂不支持
// ignore: must_be_immutable
class InAppWebViewAppRunningRecordScreen extends StatefulWidget {
  const InAppWebViewAppRunningRecordScreen({
    Key? key,
    this.assessmentId,
    this.userName,
  }) : super(key: key);

  final String? assessmentId;
  final String? userName;

  @override
  _InAppWebViewAppRunningRecordScreenState createState() =>
      new _InAppWebViewAppRunningRecordScreenState();
}

class _InAppWebViewAppRunningRecordScreenState
    extends State<InAppWebViewAppRunningRecordScreen> {
  final GlobalKey webViewKey = GlobalKey();

  InAppWebViewController? webViewController;
  InAppWebViewSettings options = InAppWebViewSettings(
      useShouldOverrideUrlLoading: true,
      mediaPlaybackRequiresUserGesture: false,
      useHybridComposition: true,
      allowsInlineMediaPlayback: true,
      allowFileAccessFromFileURLs: true,
      allowUniversalAccessFromFileURLs: true,
      cacheEnabled: true,
      domStorageEnabled: true,
      javaScriptEnabled: true,
      allowsPictureInPictureMediaPlayback: true,
      enableViewportScale: true,
      disableLongPressContextMenuOnLinks: true,
      // iframeAllow: "camera; microphone",
      // iframeAllowFullscreen: true,
      // requestedWithHeaderMode: RequestedWithHeaderMode.APP_PACKAGE_NAME,
      mixedContentMode: MixedContentMode.MIXED_CONTENT_ALWAYS_ALLOW);

  late PullToRefreshController pullToRefreshController;
  late ContextMenu contextMenu;
  String url = '';
  String _authtoken = '';
  String _numBooks = '';
  // ignore: unused_field
  String _lang = '';
  // ignore: unused_field
  String _language = '';
  String _points = '';
  String _profileSettings = '';
  //String _gender = '';
  String _assessmentId = '';
  String _userName = '';
  // ignore: unused_field
  String _url = '';

  double progress = 0;
  final urlController = TextEditingController();
  final box = Hive.box('appconfig');

  // get the CookieManager instance
  CookieManager cookieManager = CookieManager.instance();

  // set the expiration date for the cookie in milliseconds
  final expiresDate =
      DateTime.now().add(Duration(days: 3)).millisecondsSinceEpoch;

  void loadautoken() async {
    await cookieManager.deleteAllCookies();

    await cookieManager.setCookie(
      url: WebUri.uri(Uri.parse(Constants.BaseURL)),
      name: "nanhaiV4.8Role",
      value: box.get(CacheManagerKey['nanhairole'].toString()) ?? '',
      domain: Constants.BaseDomain,
      path: '/',
      expiresDate: expiresDate,
      isSecure: true,
    );

    await cookieManager.setCookie(
      url: WebUri.uri(Uri.parse(Constants.BaseURL)),
      name: "nanhaiV4.8StudentSession",
      value: box.get(CacheManagerKey['authtoken'].toString()) ?? '',
      domain: Constants.BaseDomain,
      path: '/',
      expiresDate: expiresDate,
      isSecure: true,
    );

    await cookieManager.setCookie(
      url: WebUri.uri(Uri.parse(Constants.BaseURL)),
      name: "nanhaiV4.8StudentUserId",
      value: box.get(CacheManagerKey['username'].toString()) ?? '',
      domain: Constants.BaseDomain,
      path: '/',
      expiresDate: expiresDate,
      isSecure: true,
    );

    setState(() {
      _numBooks = box.get('UserPoints').toString();
      _lang = box.get('UserLan') ?? 'Mandarin';
      _language = box.get('UserLanguage') ?? 'Simplified';
      _points = box.get('UserPoints').toString();
      _profileSettings =
          box.get(CacheManagerKey['profilesettings'].toString()) ?? '';
      _authtoken = box.get(CacheManagerKey['authtoken'].toString()) ?? '';
    });
  }

  @override
  void initState() {
    _assessmentId = widget.assessmentId ?? '';
    _userName = widget.userName ?? '';
    //Log.debug(_userName);
    loadautoken();
    // Log.debug(
    //     "${Constants.BaseURL}running-record/student/$_assessmentId/$_userName?type=part");

    pullToRefreshController = PullToRefreshController(
      // options: PullToRefreshOptions(
      //   color: Colors.blue,
      // ),
      onRefresh: () async {
        if (Platform.isAndroid) {
          webViewController?.reload();
        } else if (Platform.isIOS) {
          webViewController?.loadUrl(
              urlRequest: URLRequest(url: await webViewController?.getUrl()));
        }
      },
    );

    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        //appBar: AppBar(title: Text('Running Records')),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            Get.back();
          },
          backgroundColor: Theme.of(context).colorScheme.secondary,
          child: const Icon(Icons.close_rounded),
          tooltip: 'Close'.tr,
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.miniEndTop,
        body: SafeArea(
            child: Column(children: <Widget>[
          Expanded(
            child: Stack(
              children: [
                InAppWebView(
                  key: webViewKey,
                  // contextMenu: contextMenu,
                  initialUrlRequest: URLRequest(
                      url: WebUri.uri(Uri.parse(
                          "${Constants.BaseURL}running-record/student/$_assessmentId/$_userName?type=part")),
                      headers: {'authtoken': _authtoken}),
                  initialSettings: options,
                  pullToRefreshController: pullToRefreshController,
                  onWebViewCreated: (controller) {
                    webViewController = controller;
                  },
                  onLoadStart: (controller, url) async {
                    Log.debug(url.toString());
                    // setState(() {
                    //   this.url =
                    //       "${Constants.BaseURL}running-record/student/$_assessmentId/$_userName";

                    //   url = Uri.parse(
                    //       "${Constants.BaseURL}running-record/student/$_assessmentId/$_userName");
                    //   Log.debug(url.toString());
                    // });

                    // if (_profileSettings != '' && _userName != '') {
                    //   url = Uri.parse(url.toString() + _userName);
                    //   Log.debug(url.toString());

                    // Log.debug(
                    //     "${Constants.BaseURL}running-record/student/$_assessmentId/$_userName");
                    // await controller.evaluateJavascript(
                    //     source: "window.localStorage.setItem('lang',$_lang)");
                    // await controller.evaluateJavascript(
                    //     source:
                    //         "window.localStorage.setItem('language',$_language)");
                    await controller.evaluateJavascript(
                        source:
                            "window.localStorage.setItem('numBooks',$_numBooks)");
                    await controller.evaluateJavascript(
                        source:
                            "window.localStorage.setItem('points',$_points)");
                    await controller.evaluateJavascript(
                        source:
                            "window.localStorage.setItem('profileSettings',$_profileSettings)");
                    //controller.goForward();

                    //controller.reload();
                    // controller.loadUrl(
                    //   urlRequest: URLRequest(
                    //       url: Uri.parse(
                    //           "${Constants.BaseURL}running-record/student/$_assessmentId/$_userName"),
                    //       headers: {'authtoken': _authtoken}),
                    // );
                  },
                  onPermissionRequest: (controller, request) async {
                    return PermissionResponse(
                        resources: request.resources,
                        action: PermissionResponseAction.GRANT);
                  },
                  shouldOverrideUrlLoading:
                      (controller, navigationAction) async {
                    var uri = navigationAction.request.url!;

                    if (![
                      "http",
                      "https",
                      "file",
                      "chrome",
                      "data",
                      "javascript",
                      "about"
                    ].contains(uri.scheme)) {
                      if (await canLaunchUrl(uri)) {
                        // Launch the App
                        await launchUrl(
                          uri,
                        );
                        // and cancel the request
                        return NavigationActionPolicy.CANCEL;
                      }
                    }
                    return NavigationActionPolicy.ALLOW;
                  },
                  // onLoadStop: (controller, url) async {
                  //   List<Cookie> cookies =
                  //       await cookieManager.getCookies(url: Uri.parse(Constants.BaseURL));
                  //   cookies.forEach((cookie) {
                  //     Log.debug(cookie.name + " " + cookie.value);
                  //   });
                  // },
                  onLoadStop: (controller, url) async {
                    pullToRefreshController.endRefreshing();
                    // await controller.evaluateJavascript(
                    //     source:
                    //         "const e = document.querySelector('nav'); e.parentElement.removeChild(e);");
                    // await controller.evaluateJavascript(
                    //     source:
                    //         "const ef = document.querySelector('footer'); ef.parentElement.removeChild(ef);");
                  },
                  onReceivedError: (controller, request, error) {
                    pullToRefreshController.endRefreshing();
                  },
                  onProgressChanged: (controller, progress) {
                    if (progress == 100) {
                      pullToRefreshController.endRefreshing();
                    }
                    setState(() {
                      this.progress = progress / 100;
                      //urlController.text = this.url;
                    });
                  },
                  onUpdateVisitedHistory: (controller, url, androidIsReload) {
                    setState(() {
                      this.url = url.toString();
                      urlController.text = this.url;
                    });
                  },
                  onConsoleMessage: (controller, consoleMessage) {
                    Log.debug(consoleMessage);
                  },
                ),
                progress < 1.0
                    ? LinearProgressIndicator(value: progress)
                    : Container(),
              ],
            ),
          ),
        ])));
  }
}
